package com.leyou.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.LyEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.mapper.*;
import com.leyou.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.persistence.Transient;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public PageResult queryByPage(Integer page, Integer rows, Boolean saleable, String key) {
        PageHelper.startPage(page,rows);
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(!StringUtils.isBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }
        if(saleable!=null){
            criteria.andEqualTo("saleable",saleable);
        }
        example.setOrderByClause("last_update_time desc");
        List<Spu> list = spuMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(LyEnum.GOOD_NOT_FOUND);
        }
        loadName(list);
        PageInfo<Spu> pageInfo = new PageInfo(list);
        return new PageResult(pageInfo.getTotal(),list);
    }

    private void loadName(List<Spu> list) {
        for (Spu spu : list) {
           List<String> categories =  categoryService.queryByIds(Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3()))
                   .stream().map(category -> category.getName()).collect(Collectors.toList());
           spu.setCname(StringUtils.join(categories,"/"));
           spu.setBname(brandService.queryById(spu.getBrandId()).getName());
        }
    }

    @Transactional
    public void saveGoods(Spu spu) {
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(spu.getCreateTime());
        spu.setSaleable(true);
        spu.setValid(false);
        int insert = spuMapper.insert(spu);
        if(insert!=1){
            throw new LyException(LyEnum.GOOD_FAIL);
        }
        SpuDetail spuDetail = spu.getSpuDetail();
        spuDetail.setSpuId(spu.getId());
        insert = spuDetailMapper.insert(spuDetail);
        if(insert!=1){
            throw new LyException(LyEnum.GOOD_FAIL);
        }
        List<Stock> stocks = new ArrayList<>();
        List<Sku> skus = spu.getSkus();
        for (Sku sku : skus) {
            sku.setCreateTime(spu.getCreateTime());
            sku.setLastUpdateTime(spu.getCreateTime());
            sku.setSpuId(spu.getId());
            int count = skuMapper.insert(sku);
            if(count!=1){
                throw new LyException(LyEnum.GOOD_FAIL);
            }
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            stocks.add(stock);
        }
        stockMapper.insertList(stocks);
        amqpTemplate.convertAndSend("item.insert",spu.getId());

    }

    public List<Sku> querySkuBySpuId(Long spuId) {
        // 查询sku
        Sku record = new Sku();
        record.setSpuId(spuId);
        List<Sku> skus = this.skuMapper.select(record);
        for (Sku sku : skus) {
            // 同时查询出库存
            sku.setStock(this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
        }
        return skus;
    }

    public Spu getSpuById(Long id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu==null){
           throw new LyException(LyEnum.SPU_NOT_FOUND);
        }
        //查询sku
        List<Sku> skus = querySkuBySpuId(id);
        spu.setSkus(skus);
        //查询detail
        SpuDetail detail = spuDetailMapper.selectByPrimaryKey(id);
        spu.setSpuDetail(detail);
        return spu;
    }

    @Transactional
    public void decrease(Long id) {
        Stock stock = new Stock();
        stock.setSkuId(2600242l);
        stock.setStock(9990);
        stockMapper.updateByPrimaryKeySelective(stock);
        Log log = new Log();
        log.setOrderid(id);
        log.setSkuid(2600242l);
        logMapper.insert(log);

    }
}
